package chagine.mdt.utils;

import chagine.core.exception.SeeingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

/**
 * create by wba on  2020/3/23
 * qq:43585061
 * 处理http请求
 */
@Slf4j
public class HttpRequest {

    public final static String POST_METHOD = "POST";
    public final static String GET_METHOD = "GET";
    public final static int RESPONSE_CODE_SUCCESS = 200;
    public final static int RESPONSE_CODE_UNAUTHORIZED = 401;
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 发送post请求
     */
    public static RequestVo post(String reqUrl, Object data, Map<String, String> headers) throws SeeingException {

        try {
            URL url = new URL(reqUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-type", "application/json");
            HttpURLConnection.setFollowRedirects(true);
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod(POST_METHOD);

            //设置head
            //connection.setRequestProperty("workstation", "nurse");
            if (headers != null && !headers.isEmpty()) {
                Iterator<Map.Entry<String, String>> it = headers.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> ent = it.next();
                    connection.setRequestProperty(ent.getKey(), ent.getValue());
                }
            }

            String reqData = OBJECT_MAPPER.writeValueAsString(data);
            log.info("===========================reqData=" + reqData);
            OutputStreamWriter outWriter = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            outWriter.write(reqData);
            outWriter.flush();
            outWriter.close();
            int code = connection.getResponseCode();

            log.info("===============RESPONSE_SUCCESS===========" + code);

            if (code == RESPONSE_CODE_SUCCESS) {
                //200表示连接成功
                StringBuilder resBuilder = null;

                // 取得输入流，并使用Reader读取
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String lines;
                resBuilder = new StringBuilder();
                while ((lines = reader.readLine()) != null) {
                    resBuilder.append(lines);
                }
                reader.close();
                String respString = resBuilder.toString();

                log.info("====respString==" + respString);

//                if (!StringUtils.isEmpty(respString)) {
//                    EasemTokenRespVo respVo = OBJECT_MAPPER.readValue(respString, EasemTokenRespVo.class);
//                    respVo.setStatus(code);
//                    log.info("respVo:" + respVo.getAccessToken() + " 11" + respVo.getErrorDescription());
//                }
                RequestVo requestVo = new RequestVo();
                requestVo.setStatus(code);
                requestVo.setMessage(respString);
                return requestVo;
            } else {
                StringBuilder resBuilder = null;
                // 取得错误输入流，并使用Reader读取
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getErrorStream(), "UTF-8"));
                String lines;
                resBuilder = new StringBuilder();
                while ((lines = reader.readLine()) != null) {
                    resBuilder.append(lines);
                }
                reader.close();
                String respString = resBuilder.toString();

                log.info("====respString=1=" + respString);

//                if (!StringUtils.isEmpty(respString)) {
//                    EasemTokenRespVo respVo = OBJECT_MAPPER.readValue(respString, EasemTokenRespVo.class);
//                    respVo.setStatus(code);
//                    log.info("respVo:" + respVo.getAccessToken() + " 12" + respVo.getErrorDescription());
//
//                }

                RequestVo requestVo = new RequestVo();
                requestVo.setStatus(code);
                requestVo.setMessage(respString);
                return requestVo;

            }


        } catch (IOException e) {
            //e.printStackTrace();
            log.error("======HttpRequest=============" + e.getMessage());

        }

        return null;

    }


    /**
     * 发送post请求
     */
    public static RequestVo get(String reqUrl, Map<String, String> headers) throws SeeingException {

        try {
            log.info("---------reqUrl："+reqUrl);
            URL url = new URL(reqUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-type", "application/json");
            HttpURLConnection.setFollowRedirects(true);
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setRequestMethod(GET_METHOD);

            //设置head
            //connection.setRequestProperty("workstation", "nurse");
            if (headers != null && !headers.isEmpty()) {
                Iterator<Map.Entry<String, String>> it = headers.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> ent = it.next();
                    connection.setRequestProperty(ent.getKey(), ent.getValue());
                }
            }


            int code = connection.getResponseCode();

            log.info("===============RESPONSE_SUCCESS===========" + code);

            if (code == RESPONSE_CODE_SUCCESS) {
                //200表示连接成功
                StringBuilder resBuilder = null;

                // 取得输入流，并使用Reader读取
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String lines;
                resBuilder = new StringBuilder();
                while ((lines = reader.readLine()) != null) {
                    resBuilder.append(lines);
                }
                reader.close();
                String respString = resBuilder.toString();

                log.info("====respString==" + respString);

//                if (!StringUtils.isEmpty(respString)) {
//                    EasemTokenRespVo respVo = OBJECT_MAPPER.readValue(respString, EasemTokenRespVo.class);
//                    respVo.setStatus(code);
//                    log.info("respVo:" + respVo.getAccessToken() + " 11" + respVo.getErrorDescription());
//                }
                RequestVo requestVo = new RequestVo();
                requestVo.setStatus(code);
                requestVo.setMessage(respString);
                return requestVo;
            } else {
                StringBuilder resBuilder = null;
                // 取得错误输入流，并使用Reader读取
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getErrorStream(), "UTF-8"));
                String lines;
                resBuilder = new StringBuilder();
                while ((lines = reader.readLine()) != null) {
                    resBuilder.append(lines);
                }
                reader.close();
                String respString = resBuilder.toString();

                log.info("====respString=1=" + respString);

//                if (!StringUtils.isEmpty(respString)) {
//                    EasemTokenRespVo respVo = OBJECT_MAPPER.readValue(respString, EasemTokenRespVo.class);
//                    respVo.setStatus(code);
//                    log.info("respVo:" + respVo.getAccessToken() + " 12" + respVo.getErrorDescription());
//
//                }

                RequestVo requestVo = new RequestVo();
                requestVo.setStatus(code);
                requestVo.setMessage(respString);
                return requestVo;

            }


        } catch (IOException e) {
            //e.printStackTrace();
            log.error("======HttpRequest=============" + e.getMessage());

        }

        return null;

    }


}
